package com.zxy.study.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Choreographer;

import com.zxy.study.R;
import com.zxy.study.adapter.MainAdapter;
import com.zxy.study.base.recyclerview.BlueRecyclerViewDivider;
import com.zxy.study.bean.HomeBean;
import com.zxy.study.ui.photoview.ScalePhotoViewActivity;
import com.zxy.study.utils.LifeCycleLog;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import static android.os.Environment.DIRECTORY_PICTURES;


public class MainActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;
    private static MyFrameCallback mFrameCallback = new MyFrameCallback();
    @SuppressLint("HandlerLeak")
    private static Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Log.i("AAA", "sm=" + mFrameCallback.getSm() + " skipFrame=" + mFrameCallback.getSkipFrame());
            mHandler.sendEmptyMessageDelayed(0, 1000);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mRecyclerView = findViewById(R.id.recyclerview);
        initView();

        LifeCycleLog.logCreate(MainActivity.class);

//        mHandler.sendEmptyMessage(0);
//        Choreographer.getInstance().postFrameCallback(mFrameCallback);
//        Build.DEVICE
        testAccessFile(this);

        LifeCycleLog.logCurTaskInfo(this);

    }

    public void testAccessFile(Context context){
        Log.d("AAA","------------------Context:");
        Log.d("AAA","getCacheDir:"+context.getCacheDir().getAbsolutePath());
        Log.d("AAA","getFilesDir:"+context.getFilesDir().getAbsolutePath());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Log.d("AAA","getDataDir:"+context.getDataDir().getAbsolutePath());
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Log.d("AAA","getFilesDir:"+context.getCodeCacheDir().getAbsolutePath());
        }
        Log.d("AAA","getExternalCacheDir:"+context.getExternalCacheDir().getAbsolutePath());
        Log.d("AAA","getExternalFilesDir(DIRECTORY_PICTURES):"+context.getExternalFilesDir(DIRECTORY_PICTURES).getAbsolutePath());
        Log.d("AAA","------------------Environment:");
        Log.d("AAA","getDataDirectory:"+ Environment.getDataDirectory().getAbsolutePath());
        Log.d("AAA","getExternalStorageState:"+Environment.getExternalStorageState());
        Log.d("AAA","getDownloadCacheDirectory:"+Environment.getDownloadCacheDirectory().getAbsolutePath());
        Log.d("AAA","getRootDirectory:"+Environment.getRootDirectory().getAbsolutePath());
        Log.d("AAA","getExternalStorageDirectory:"+Environment.getExternalStorageDirectory().getAbsolutePath());
        Log.d("AAA","getExternalStoragePublicDirectory:"+Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES).getAbsolutePath());
    }


    private void initView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        BlueRecyclerViewDivider divider = new BlueRecyclerViewDivider.Builder(this).setDividerColorRes(R.color.colorPrimary).setVerticalDivider(1, true).build();
        mRecyclerView.addItemDecoration(divider);
        MainAdapter mainAdapter = new MainAdapter(getDataList());
        mRecyclerView.setAdapter(mainAdapter);

        mainAdapter.setItemClickListener((adapter, view, dataPos) -> start(mainAdapter.getItemData(dataPos).getClazz()));
    }

    private String[] itemTitles = {"头部缩放图", "协调布局-文本移动标题效果", "ToolBar", "可收缩的ToolBar", "仿UC浏览器效果", "矢量动画", "手写签名",
            "自定义Tab标题栏", "可缩放View", "OpenGl", "Camera3D旋转", "mvvm测试", "ViewPager2", "自定义倒计时控件", "滚动到指定位置", "测试界面测量次数", "EasyImage","LiveData"};
    private Class[] itemClicks = {HeadZoomViewActivity.class, MoveTextToTitleActivity.class, ToolBarActivity.class, CollapsingToolbarActivity.class,
            UCDemoActivity.class, VectorAnimatorActivity.class, SignatureActivity.class, TextTabAvtivity.class, ScalePhotoViewActivity.class,
            OpenGLActivity.class, CameraViewActivity.class, MVVMDemoActivity.class, ViewPager2Activity.class, CountDownActivity.class, ScrollToPositionActivity.class,
            TestMeasureTimesActivity.class, EasyImageActivity.class,MvvmActivity.class};

    private List<HomeBean> getDataList() {
        List<HomeBean> resultList = new ArrayList<>();
        for (int i = 0; i < itemTitles.length; i++) {
            resultList.add(new HomeBean(itemTitles[i], itemClicks[i]));
        }
        return resultList;
    }

    private void start(Class<?> clazz) {
        startActivity(new Intent(this, clazz));

//        long start = System.currentTimeMillis();
//        Log.d("AAA","EasyProtectorLib start");
//        boolean isEmulator2 = EasyProtectorLib.checkIsRunningInEmulator(this,null/* emulatorInfo -> Log.d("AAA", emulatorInfo)*/);
//        Log.d("AAA","EasyProtectorLib end cost time = "+(System.currentTimeMillis() - start));
//
//        start = System.currentTimeMillis();
//        Log.d("AAA","BlueEmulatorDetectUtil start");
//        boolean isEmulator = BlueEmulatorDetectUtil.INSTANCE.checkIsRunningInEmulator(this, emulatorInfo -> Log.d("AAA", emulatorInfo));
//        Log.d("AAA","BlueEmulatorDetectUtil end cost time = "+(System.currentTimeMillis() - start));
//
//        Log.d("AAA","这个是模拟器吗="+ isEmulator);
    }

    @Override
    protected void onStart() {
        super.onStart();
        LifeCycleLog.logStart(MainActivity.class);
    }

    @Override
    protected void onResume() {
        super.onResume();
        LifeCycleLog.logResume(MainActivity.class);
    }

    @Override
    protected void onPause() {
        super.onPause();
        LifeCycleLog.logPause(MainActivity.class);
    }

    @Override
    protected void onStop() {
        super.onStop();
        LifeCycleLog.logStop(MainActivity.class);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LifeCycleLog.logDestroy(MainActivity.class);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        LifeCycleLog.logSaveInstanceState(MainActivity.class);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        LifeCycleLog.logRestoreInstanceState(MainActivity.class);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Log.d("lifecycle", "MainActivity onConfigurationChanged");
    }

    public static class MyFrameCallback implements Choreographer.FrameCallback {
        private String TAG = "性能检测";
        private long lastTime = 0;
        private int sm = 0;
        private int skipFrame = 0;

        @Override
        public void doFrame(long frameTimeNanos) {
            sm++;
            if (lastTime == 0) {
                //代码第一次初始化。不做检测统计。
                lastTime = frameTimeNanos;
            } else {
                double times = (frameTimeNanos - lastTime) / 1000000f;
                int frames = (int) (times / 16.6f);

                if (times > 16.6f) {
//                    Log.w(TAG, "UI线程超时(超过16ms):" + times + "ms" + " , 丢帧:" + frames);
                    skipFrame++;
                }

                lastTime = frameTimeNanos;
            }

            Choreographer.getInstance().postFrameCallback(mFrameCallback);
        }

        public int getSm() {
            int times = sm;
            sm = 0;
            return times;
        }

        public int getSkipFrame() {
            int times = skipFrame;
            skipFrame = 0;
            return times;
        }
    }

}
